package h0919;
/**
  * @description 接雨水
  * @author 不知名帅哥
  * @date 2024/9/19 18:32
  * @version 1.0
*/
public class TrappingRainWater {

    public int trap(int[] height) {
        if (height == null || height.length == 0) {
            return 0;
        }

        int left = 0, right = height.length - 1;
        int leftMax = height[left], rightMax = height[right];
        int totalWater = 0;

        while (left<right){
            //能存放的水量是由短板来决定的。所以哪个小，哪个就当作被减数。然后累加
            if (leftMax<rightMax){
                left++;
                leftMax=Math.max(leftMax,height[left]);
                totalWater+=leftMax-height[left];
            }else {
                right--;
                rightMax=Math.max(rightMax,height[right]);
                totalWater+=rightMax-height[right];
            }
        }

        return totalWater;
    }

    public static void main(String[] args) {
        TrappingRainWater solution = new TrappingRainWater();
        int[] height = {5,4,3,2,1,2};
        System.out.println(solution.trap(height));  // 输出应该是6
    }
}
